<template>
  <div class="page-content">
    <h3>分销等级</h3>
    <el-row style="margin-top: 20px">
      <div style="width: 12px"></div>
      <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
        <el-button @click="showDialog('add')" v-ripple>新增等级</el-button>
      </el-col>
    </el-row>

    <art-table :data="tableData.length ? tableData : demoData">
      <template #default>
        <el-table-column label="权重等级" prop="sortOrder" align="center" />
        <el-table-column label="等级名称" prop="levelName" align="center" />
        <el-table-column label="等级规则" prop="typename" align="center">
          <template #default="scope">
            <div>累计绑定客户：{{ scope.row.ruleCustomerCount }}人</div>
            <div>客户累计消费：{{ scope.row.ruleCustomerAmount }}元</div>
            <div>累计邀请推广员：{{ scope.row.ruleAgentCount }}人</div>
          </template>
        </el-table-column>
        <el-table-column label="默认商品佣金比例" prop="firstPercent" align="center">
          <template #default="scope">
            {{ scope.row.firstPercent !== 0 ? `${(scope.row.firstPercent * 100) / 10000}%` : 0 }}
          </template>
        </el-table-column>
        <el-table-column label="默认邀请人奖励比例" prop="secondPercent" align="center">
          <template #default="scope">
            {{ scope.row.secondPercent !== 0 ? `${(scope.row.secondPercent * 100) / 10000}%` : 0 }}
          </template>
        </el-table-column>
        <el-table-column #default="scope" label="启用状态" align="center">
          <el-switch v-model="scope.row.state" :active-value="1" :inactive-value="0"
            :disabled="scope.row.sortOrder === 1" @click="editState(scope.row)" />
        </el-table-column>
        <el-table-column label="创建时间：" prop="date" align="center">
          <template #default="scope">
            {{ scope.row.createTime ? formatDate(scope.row.createTime) : '' }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150px" align="center">
          <template #default="scope">
            <button-table type="edit" @click="buttonMoreClick(scope.row)" />
            <button-table type="delete" @click="deleteRole(scope.row.id, scope.row.sortOrder)" v-if="settingData.brokerageMode !== '02'" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增等级' : '编辑等级'" width="30%" :close-on-click-modal="false">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="140px">
        <el-form-item label="等级名称" prop="levelName">
          <el-input v-model="formData.levelName" />
        </el-form-item>
        <el-form-item label="等级规则">
          <el-checkbox-group v-model="checkedItems" :disabled="formData.sortOrder === 1 || (dialogType === 'edit' && settingData.brokerageMode === '02')">
            <div v-for="item in options" :key="item.value" style="margin-bottom: 10px">
              <el-checkbox :value="item.value">{{ item.label }}</el-checkbox>
              <el-input v-if="checkedItems.includes(item.value)" v-model="inputValues[item.value]"
                :disabled="formData.sortOrder === 1 || (dialogType === 'edit' && settingData.brokerageMode === '02' && item.value !== '3')" controls-position="right" style="width: 200px; margin-left: 30px">
                <template #append>{{ item.type }}</template>
              </el-input>
            </div>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="默认商品佣金比例">
          <el-input v-model="formData.firstPercent" style="width: 200px" placeholder="请输入商品佣金比例（%）">
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="默认邀请人奖励比例">
          <el-input v-model="formData.secondPercent" style="width: 200px" placeholder="请输入邀请人奖励比例（%）">
            <template #append>%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)" :loading="editLoading">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useMenuStore } from '@/store/modules/menu'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { formatMenuTitle } from '@/router/utils/utils'
import {
  promotionLevel,
  addPromotionLevel,
  editLevelState,
  delPromotionLevel,
  editLevelInfo,
  getDefault
} from '@/api/marketing'

const dialogVisible = ref(false)

const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({})
interface Option {
  label: string
  value: string
  type: string
}
const options: Option[] = [
  { label: '累计绑定客户', value: '1', type: '人' },
  { label: '客户累计消费', value: '2', type: '元' },
  { label: '累计邀请推广员', value: '3', type: '人' }
]
const checkedItems = ref<string[]>([])
const inputValues = ref<{ [key: string]: string }>({})

const formData = reactive({
  id: '',
  levelName: '',
  firstPercent: 10,
  secondPercent: 10,
  ruleCustomerCount: '',
  ruleCustomerAmount: '',
  ruleAgentCount: '',
  sortOrder: 0,
  parentId: 0
})

const settingData = ref<any>({})

const tableData = ref([

])
const demoData = ref([{
  id: '',
  sortOrder: 1,
  parentId: 0,
  levelName: '默认等级',
  ruleCustomerCount: '0',
  ruleCustomerAmount: '0',
  ruleAgentCount: '0',
  firstPercent: 1000,
  secondPercent: 1000,
  state: 1
}])

const dialogType = ref('add')

const showDialog = (type: string, row?: any) => {
  dialogVisible.value = true
  dialogType.value = type

  if (type === 'edit' && row) {
    formData.id = row.id
    formData.levelName = row.levelName
    formData.firstPercent = (row.firstPercent * 100) / 10000
    formData.secondPercent = (row.secondPercent * 100) / 10000
    // 先清空输入框
    inputValues.value['1'] = ''
    inputValues.value['2'] = ''
    inputValues.value['3'] = ''
    // 回填选中项
    const checked: string[] = []
    if (row.ruleCustomerCount !== '' && row.ruleCustomerCount !== null && row.ruleCustomerCount !== undefined) {
      checked.push('1')
      inputValues.value['1'] = row.ruleCustomerCount
    }
    if (row.ruleCustomerAmount !== '' && row.ruleCustomerAmount !== null && row.ruleCustomerAmount !== undefined) {
      checked.push('2')
      inputValues.value['2'] = row.ruleCustomerAmount
    }
    if (row.ruleAgentCount !== '' && row.ruleAgentCount !== null && row.ruleAgentCount !== undefined) {
      checked.push('3')
      inputValues.value['3'] = row.ruleAgentCount
    }
    checkedItems.value = checked
    formData.sortOrder = row.sortOrder
    formData.parentId = row.parentId
  } else {
    formData.id = ''
    formData.levelName = ''
    formData.firstPercent = 10
    formData.secondPercent = 10
    checkedItems.value = []
    inputValues.value['1'] = ''
    inputValues.value['2'] = ''
    inputValues.value['3'] = ''
    formData.sortOrder = 0
  }
}

const buttonMoreClick = (row: any) => {
  showDialog('edit', row)
}

const deleteRole = (id: string, sortOrder: number) => {
  if (sortOrder === 1) {
    ElMessage.warning('系统默认等级不允许删除')
  } else {
    ElMessageBox.confirm('确定删除该等级吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
      const res = await delPromotionLevel(id)
      if (res.code === '00000') {
        ElMessage.success('删除成功')
        getData()
      }
    })
  }
}

const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
      result[key] = obj[key]
    }
  }
  return result
}

interface lastItem {
  sortOrder: number
  id: string
  parentId: number
}
const lastList = ref<lastItem>({
  sortOrder: 0,
  id: '',
  parentId: 0
})
const editLoading = ref(false)
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      console.log(inputValues.value, 'inputValues===')
      lastList.value = tableData.value[tableData.value.length - 1]
      if (formData.id) {
        try {
          const params: any = {
            ruleCustomerCount: checkedItems.value.includes('1') ? inputValues.value[1] : '0',
            ruleCustomerAmount: checkedItems.value.includes('2') ? inputValues.value[2] : '0',
            ruleAgentCount: checkedItems.value.includes('3') ? inputValues.value[3] : '0',
            firstPercent: Number(formData.firstPercent) * 100,
            secondPercent: Number(formData.secondPercent) * 100,
            levelName: formData.levelName,
            parentId: formData.parentId,
            sortOrder: formData.sortOrder
          }
          editLoading.value = true
          params.id = formData.id
          const res = await editLevelInfo(filterEmptyValues(params))
          if (res.code === '00000') {
            ElMessage.success('编辑成功')
            dialogVisible.value = false
            getData()
          }
        } catch {
        } finally {
          editLoading.value = false
        }
      } else {
        try {
          const params: any = {
            sortOrder: tableData.value.length ? lastList.value.sortOrder + 1 : 1,
            ruleCustomerCount: checkedItems.value.includes('1') ? inputValues.value[1] : '0',
            ruleCustomerAmount: checkedItems.value.includes('2') ? inputValues.value[2] : '0',
            ruleAgentCount: checkedItems.value.includes('3') ? inputValues.value[3] : '0',
            firstPercent: Number(formData.firstPercent) * 100,
            secondPercent: Number(formData.secondPercent) * 100,
            levelName: formData.levelName,
            bindType: 0
          }
          if (tableData.value.length) {
            params.parentId = lastList.value.id
          }
          editLoading.value = true
          const res = await addPromotionLevel(filterEmptyValues(params))
          if (res.code === '00000') {
            ElMessage.success('新增成功')
            dialogVisible.value = false
            getData()
          }
        } catch {
        } finally {
          editLoading.value = false
        }
      }
    }
  })
}

const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}

const getData = async () => {
  try {
    const res = await promotionLevel()
    if (res.code === '00000' && res.data.length) {
      tableData.value = res.data
    }
  } catch {
  } finally {
  }
}

const getSettingData = async () => {
  try {
    const res = await getDefault()
    if (res.code === '00000' && res.data) {
      settingData.value = res.data
    }
  } catch {
  } finally {
  }
}

const editState = async (e: any) => {
  console.log(e, "e===");
  if (e.sortOrder !== 1) {
    try {
      const res = await editLevelState(e.id, e.state)
      if (res.code === '00000') {
        ElMessage.success('状态修改成功')
        getData()
      }
    } catch { } finally {
      getData()
    }
  }
}
onMounted(() => {
  getData()
  getSettingData()
})
</script>

<style lang="scss" scoped>
.page-content {
  .svg-icon {
    width: 1.8em;
    height: 1.8em;
    overflow: hidden;
    vertical-align: -8px;
    fill: currentcolor;
  }
}

.el-checkbox.el-checkbox--large {
  width: 150px;
}
</style>
